package com.example.shop_2305.fg

import android.content.Context
import android.hardware.camera2.CameraExtensionSession.StillCaptureLatency
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.example.lib_base.mvvm.BaseFragment
import com.example.lib_base.net.LiveDataBus
import com.example.shop_2305.R
import com.example.shop_2305.adapter.CouponAdapter
import com.example.shop_2305.adapter.GoodsAdapter
import com.example.shop_2305.adapter.MenuAdapter
import com.example.shop_2305.adapter.TypeAdapter
import com.example.shop_2305.databinding.FragmentHomeBinding
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import kotlinx.coroutines.launch
import kotlin.concurrent.timer


class HomeFragment : BaseFragment<FragmentHomeBinding,HomeViewModel>() {
    val imgs = mutableListOf<String>()//轮播图地址
    lateinit var menuAdapter: MenuAdapter
    lateinit var couponAdapter: CouponAdapter
    lateinit var typeAdapter: TypeAdapter
    lateinit var goodsAdapter: GoodsAdapter
    var page = 1
    var type = 4 //分类默认为4   因为数据的第一条的type为4
    override fun initView() {

        menuAdapter = MenuAdapter()
        binding.rvMenu.adapter = menuAdapter
        binding.rvMenu.layoutManager = GridLayoutManager(context,5)

        //优惠券初始化
        couponAdapter = CouponAdapter()
        binding.rvCoupon.adapter = couponAdapter
        binding.rvCoupon.layoutManager = LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false)

        //分类 初始化
        typeAdapter = TypeAdapter()
        binding.rvType.adapter = typeAdapter
        binding.rvType.layoutManager = GridLayoutManager(context,4)

        viewModel.coupon("10","1","1")//只请求10条

        //点击跳转到搜索界面
        binding.llSearch.setOnClickListener {
            ARouter.getInstance().build("/app/SearchActivity").navigation()
        }
        viewModel.index()

        //初始化商品数据
        goodsAdapter = GoodsAdapter()
        binding.rvGoods.adapter = goodsAdapter
        binding.rvGoods.layoutManager =GridLayoutManager(context,2)

        viewModel.indexGoods(type,5,page)

        //点击分类item,下方商品数据发生变化
        typeAdapter.setOnItemClickListener { adapter, view, position ->
            type  = typeAdapter.data[position].type.toInt()
            page = 1 //点击分类进行切换时，页码一定是从1开始的
            typeAdapter.setType(type)
            viewModel.indexGoods(type,5,page)
        }
        //刷新加载更多
        binding.smart.setOnRefreshLoadMoreListener(object :OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
               page = 1
                viewModel.indexGoods(type,5,page)
                binding.smart.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                viewModel.indexGoods(type,5,page)
                binding.smart.finishLoadMore()
            }
        })
        //点击优惠券进行领取
        couponAdapter.setOnItemClickListener { adapter, view, position ->
            //只有未领取的优惠可进行领取
            if(!couponAdapter.data[position].isUse){
                viewModel.couponGet(couponAdapter.data[position].id)
                //直接改变页面
                (couponAdapter.getViewByPosition(position,R.id.coupon_get) as TextView).text = "已领取"
                couponAdapter.data[position].isUse = true//修改适配器中的值 这样就不会再次调用
            }else{
                ToastUtils.showLong("不能重复领取")
            }
        }

        //点击商品列表，跳转到详情界面
        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/app/DetailActivity").withInt("gid",goodsAdapter.data[position].id).navigation()
        }
        //点击分类，跳转到新的分类界面
        menuAdapter.setOnItemClickListener { adapter, view, position ->
            when(position){
                0->ARouter.getInstance().build("/app/CateActivity").navigation()
                1->ARouter.getInstance().build("/app/CarActivity").navigation()
                2->{
                    LiveDataBus.instance.sendEvent("button3","点击了第三个菜单")
                }
                3->{
                    LiveDataBus.instance.sendEvent("button4","点击了第四个菜单")
                }
            }
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                LiveDataBus.instance.getEvent<String>("button3").observeForever {
                    ToastUtils.showLong(it)
                }
                LiveDataBus.instance.getEvent<String>("button4").observeForever {
                    ToastUtils.showLong(it)
                }
        }

        }

       /* LiveDataBus.instance.getEvent<String>("button3").observe(this){
            ToastUtils.showLong(it)
        }*/
    }

    override fun initData() {


    /*    LiveDataBus.instance.getEvent<String>("button3").observe(this){
            ToastUtils.showLong(it)
        }*/
        viewModel.indexSuccess.observe(this){
            if(it.code==200){
                //显示轮播图
                it.data.banner.forEach {
                    imgs.add(it.pic)
                }
                binding.banner.setImages(imgs)
                    .setImageLoader(object :ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            if (context != null&&imageView!=null) {
                                Glide.with(context).load(path).into(imageView)
                            }
                        }

                    })
                    .setDelayTime(2000)//轮播时长
                    .setOnBannerListener {
                        ToastUtils.showLong("点击的是第$it 张图片")
                    }
                    .setBannerStyle(BannerConfig.NUM_INDICATOR)
                    .start()
                //加载菜单栏
                menuAdapter.data.clear()
                menuAdapter.data.addAll(it.data.menus)
                menuAdapter.notifyDataSetChanged()
                //加载分类
                typeAdapter.data.clear()
                typeAdapter.data.addAll(it.data.explosiveMoney)
                typeAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        //优惠券请求结果
        viewModel.couponSuccess.observe(this){
            if(it.code==200){
                couponAdapter.data.clear()
                couponAdapter.data.addAll(it.data)
                couponAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.couponFail.observe(this){
            ToastUtils.showLong(it)
        }
        //商品数据请求结果
        viewModel.indexGoodsSuccess.observe(this){
            if(it.code==200){
                //当页面为1时，要么是初始化 要么是刷新的结果  这种情况去清空数据
                if(page==1){
                    goodsAdapter.data.clear()
                }
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
                //当没有更多数据展示时，给出提示
                if(it.data.list.size==0){
                    ToastUtils.showLong("没有更多数据可加载了")
                }
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.indexGoodsFail.observe(this){
            ToastUtils.showLong(it)
        }

        viewModel.couponGetSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.couponGetFail.observe(this){
            ToastUtils.showLong(it)
        }
    }

    override fun getViewModel(): Class<HomeViewModel>  = HomeViewModel::class.java

    override fun getLayout(): Int = R.layout.fragment_home

    //关闭轮播图 防止内存泄露
    override fun onDestroyView() {
        super.onDestroyView()
        binding.banner.stopAutoPlay()
    }

}